package com.authine.cloudpivot.ext.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.enums.ErrCode;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author chenjq
 * @date 2021/7/28
 */
@Api(value = "更新业务对象字段值", tags = "ExtApi::更新业务对象字段值")
@RestController
@RequestMapping("/ext/biz_object_property")
@Slf4j
public class BizObjectPropertyController extends BaseController {

    @SuppressWarnings("unchecked")
    @ApiOperation("更新业务对象字段值")
    @PostMapping(value = "/update_value")
    public ResponseResult updatePropertyValue(@RequestBody JSONObject params) {
        log.info("=========== 更新业务对象字段值: {} ==========", params.toJSONString());
        // 业务对象ID
        String id = params.getString("id");
        // 模型编码
        String schemaCode = params.getString("schemaCode");
        JSONArray property = params.getJSONArray("property");
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(schemaCode, id);
        for (int i = 0; i < property.size(); i++) {
            JSONObject jsonObject = property.getJSONObject(i);
            String key = jsonObject.getString("key");
            BizPropertyModel bizProperty = getAppManagementFacade().getBizProperty(schemaCode, key);
            if (BizPropertyType.CHILD_TABLE == bizProperty.getPropertyType()) {
                bizObject.getData().put(key, JSONArray.parseArray(jsonObject.getJSONArray("value").toJSONString(), Map.class));
            } else {
                bizObject.getData().put(key, jsonObject.getString("value"));
            }
        }
        getBizObjectFacade().saveBizObject(bizObject.getOwner().getId(), bizObject, true);
        return getOkResponseResult(ErrCode.OK.getErrMsg());
    }

}
